<script setup lang="ts">
import { searchSupplierRel } from '@/api/material/material/';
import { onMounted } from 'vue';
import { useVModel } from '@vueuse/core';
import { MaterialSearchVO } from '@/api/material/material/types';

const props = defineProps<{
  modelValue?: MaterialSearchVO[] | MaterialSearchVO;
  multiple?: boolean;
  materialId?: string | number | null;
}>();
const emit = defineEmits(['update:modelValue']);
const value = useVModel(props, 'modelValue', emit);
const loading = ref(false);
const list = ref<MaterialSearchVO[]>([]);

const getData = async (params?: any) => {
  if (loading.value) return;
  loading.value = true;
  const _list = await searchSupplierRel(params);
  // 根据Id去重，并根据函数处理重复项数据
  loading.value = false;
  list.value = _list.data;
};

const _value = computed({
  get: () => {
    if (!value.value) return null;
    if (props.multiple) {
      return (value.value as MaterialSearchVO[]).map((x) => x.materialId);
    } else {
      return (value.value as MaterialSearchVO).materialId;
    }
  },
  set: (val: string | string[]) => {
    let _list = list.value.filter((x) => {
      if (props.multiple) {
        return (val as any[]).includes(x.materialId);
      } else {
        return (val as string) === x.materialId;
      }
    });
    value.value = props.multiple ? _list : _list[0];
  }
});

onMounted(async () => {
  await getData({ materialId: props.materialId });
});

const remoteMethod = (query: string) => {
  getData({ materialId: props.materialId, text: query });
};
</script>

<template>
  <el-select
    v-model="_value"
    v-bind="$attrs"
    :multiple="props.multiple"
    filterable
    remote
    reserve-keyword
    placeholder="请选择物料"
    :remote-method="remoteMethod"
    :loading="loading"
  >
    <slot :list="list">
      <el-option v-for="item in list" :key="item.relId" :label="item.materialCode" :value="item.materialId + item.supplierId">
        <span style="float: left">{{ item.materialCode }}</span>
        <span style="float: right; color: var(--el-text-color-secondary); font-size: 13px">
          {{ item.companyName }}
        </span>
      </el-option>
    </slot>
  </el-select>
</template>

<style scoped lang="scss"></style>
